package com.es.dao.impl;

import com.es.dao.StudentDao;
import com.es.entity.Student;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class StudentDaoImpl implements StudentDao {

    private JdbcTemplate jdbcTemplate;

    @Override
    public int save(Student student) {
        //先开事务
        String sql = "insert into student(name) values (?)";
        int i  = jdbcTemplate.update(sql, student.getName());
        //
        int j = 10/0;

        return i;
    }

    @Override
    public int update(Student student) {
        String sql = "update student set name = ? where id = ?";
        return jdbcTemplate.update(sql, student.getName(), student.getId());
    }

    @Override
    public int delete(Integer id) {
        String sql = "delete from student where id = ?";
        return jdbcTemplate.update(sql, id);
    }

    @Override
    public List<Student> list() {
        String sql = "select id,name from student";
        List<Student> list = jdbcTemplate.query(sql, new StudentMapper());
        return list;
    }

    @Override
    public Student get(Integer id) {
        String sql = "select id,name from student where id = ? ";
        Student student = jdbcTemplate.queryForObject(sql, new StudentMapper(), id);
        return student;
    }

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    private class StudentMapper implements RowMapper<Student>{

        @Override
        public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
            Student stu = new Student();
            stu.setName(rs.getString("name"));
            stu.setId(rs.getInt("id"));
            return stu;
        }
    }

}
